<?php
/**
 * Created by PhpStorm.
 * Author: yostar
 * User: THINK
 * Date: 2018/6/2
 * Time: 10:29
 */

namespace wechat\model;

require_once '../config.php';

class Common
{
    public $wechat_config = [
        'app_id' => 'wxa437eb7ff2c08e81', // wxcb744e6720692a96
        'app_secret' => '785c1ad3bc8740c9bce15e8ff24ed00c', //45e8d739b6595d94afce8d2f9db4e3d7
        'expires_time' => 7100,
        'getAccessTokenUrl' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
        'addCustomerServiceAccountUrl' => 'https://api.weixin.qq.com/customservice/kfaccount/add?access_token=%s',
        'deleteCustomerServiceAccountUrl' => 'https://api.weixin.qq.com/customservice/kfaccount/del?access_token=%s',
        'updateCustomerServiceAccountUrl' => 'https://api.weixin.qq.com/customservice/kfaccount/update?access_token=%s',
        'getCustomerServiceListUrl' => 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=%s',
        'createMenuUrl' => 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s',
        'getMenuUrl' => 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s',
        'deleteMenuUrl' => 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s',
        'uploadTemporaryMaterialUrl' => 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s',
        'oauthUrl' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=123#wechat_redirect',
        'uploadPermanentMaterialUrl' => 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=%s',
        'getMaterialListUrl' => 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=%s',
        'getMaterialTotalUrl' => 'https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=%s',
        'updateNewsUrl' => 'https://api.weixin.qq.com/cgi-bin/material/update_news?access_token=%s',
        'addNewsUrl' => 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=%s',
        'deleteMaterialUrl' => 'https://api.weixin.qq.com/cgi-bin/material/del_material?access_token=%s',
        'getMaterialUrl' => 'https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=%s',
        'getUserBaseInfoUrl' => 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN',
    ];

    /**
     * 日志记录
     * @param $data
     * @param string $file
     */
    public function log($data, $file = 'logs.txt')
    {

        file_put_contents($file, date("Y-m-d H:i:s", time()) . ": " . $data . PHP_EOL, FILE_APPEND);
    }

    /**
     * // 获取get_access_token
     * @return mixed
     */
    public function get_access_token()
    {
        session_start(); // 开启session
        $time = 7200;
        if (isset($_SESSION['created_at'])) {
            $time = time() - $_SESSION['created_at']; // 计算距access_token生成已过去的时间
        }
        // 如果超过设置的时间，就再次请求
        if ($time > $this->wechat_config['expires_time']) {
            session_destroy();
            $url = $this->getAccessTokenUrl();
            $data = $this->curl_get($url);
            // 用session保存数据
            $_SESSION['access_token'] = $data['access_token'];
            $_SESSION['expires_in'] = $data['expires_in'];
            $_SESSION['created_at'] = time();
        }
        return $_SESSION['access_token'];
    }

    /**
     *  curl Get 方法
     * @param $url
     * @return mixed
     */
    protected function curl_get($url)
    {
        $ch_instance = curl_init($url);
        // 不带消息头
        curl_setopt($ch_instance, CURLOPT_HEADER, false);
        // 结果为字符串并打印到屏幕
        curl_setopt($ch_instance, CURLOPT_RETURNTRANSFER, true);
        // 不检查证书合法性
        curl_setopt($ch_instance, CURLOPT_SSL_VERIFYPEER, false);
        // 不检查加密算法
        curl_setopt($ch_instance, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch_instance);
        curl_close($ch_instance);
        return json_decode($result, true);
    }

    /**
     * post 提交数据
     * @param $postData
     * @param $url
     * @return mixed|null
     */
    protected function curl_post($postData, $url)
    {
        if (!$postData) {
            return false;
        }
        $post_curl = curl_init();
        // 设置访问链接
        curl_setopt($post_curl, CURLOPT_URL, $url);
        // 强制curl模块使用CURLFile式的文件，拒绝@语法
        curl_setopt($post_curl, CURLOPT_SAFE_UPLOAD, true);
        // 结果为字符串并打印到屏幕
        curl_setopt($post_curl, CURLOPT_RETURNTRANSFER, true);
        // 不带消息头
        curl_setopt($post_curl, CURLOPT_HEADER, false);
        // 不检查证书合法性
        curl_setopt($post_curl, CURLOPT_SSL_VERIFYPEER, false);
        // 使用post方法
        curl_setopt($post_curl, CURLOPT_POST, true);
        // 携带post参数
        curl_setopt($post_curl, CURLOPT_POSTFIELDS, json_encode($postData, JSON_UNESCAPED_UNICODE));
        $result = curl_exec($post_curl);
        // 关闭资源
        curl_close($post_curl);
        return json_decode($result, true);
    }

    /**
     * 合成access_token请求地址
     * @return mixed|string
     */
    private function getAccessTokenUrl()
    {
        $url = $this->wechat_config['getAccessTokenUrl'];
        return sprintf($url, $this->wechat_config['app_id'], $this->wechat_config['app_secret']);
    }

    /**
     * 格式化只需要输入access_token的url
     * @param $url
     * @return string
     */
    public function formatUrlWithToken($url)
    {
        return sprintf($url, $this->get_access_token());
    }

    /**
     * 格式化输出
     * @param $data
     */
    public function dd($data)
    {
        echo "<pre>";
        print_r($data);
        echo "</pre>";
        die();
    }

    /**
     * 获取用户基本信息
     * @param $openid
     * @return mixed
     */
    public function getBaseUserInfo($openid)
    {
        $url = sprintf( $this->wechat_config['getUserBaseInfoUrl'], $this->get_access_token(), $openid);
        $result = $this->curl_get($url);
        return $result;
    }
}